import UploadPreview from "@/components/UploadPreview";
import { TOKEN } from "@/constants";
import { getItem } from "@/utils/localstorage";
import { DeleteOutlined, InfoCircleOutlined } from "@ant-design/icons";
import { PageContainer, ProDescriptions } from "@ant-design/pro-components";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-react";
import { Button, Card, Flex, Image, Tooltip, Spin, message, Tag } from "antd";
import { FC, useEffect, useState } from "react";
import styles from "../index.less";
import Https from "@/utils/Https";
import Https2 from "@/utils/Https2";
import { hexToRgba } from "../configFile";
import { connect } from "umi";
import authorPng from "@/assets/imgs/author.png";
import dayjs from "dayjs";
const BrandBasic: FC<any> = (props) => {
  const { onSuccess, dispatch } = props;
  const [brandImg, setBrandImg] = useState("");
  const [editor, setEditor] = useState(null);
  const [loading, setLoading] = useState(false);
  const [brandInfo, setBrandInfo] = useState<any>({});
  const [byTypeList, setByTypeList] = useState({});
  // 编辑器内容
  const [html, setHtml] = useState("");
  type InsertFnType = (url: string, alt: string, href: string) => void;
  const editorConfig = {
    placeholder: "请输入品牌介绍", // JS 语法
    MENU_CONF: {
      uploadImage: {
        fieldName: "file",
        server: "/spark-frontend/system/user/uploadPic",
        allowedFileTypes: ["image/*"],
        headers: {
          clientid: "e5cd7e4891bf95d1d19206ce24a7b32e",
          Authorization: getItem(TOKEN),
        },
        customInsert(res: any, insertFn: InsertFnType) {
          if (res?.code == 200) {
            let { data } = res;
            insertFn(data, "", "");
          }
        },
      },
    },
  };
  const getByType = async () => {
    let res = await Https2.post(
      "/system/dict/data/byType",
      { dictType: "business_type" },
      true
    );
    if (res.code == 200) {
      let obj = {};
      if (res.data.length > 0) {
        res.data.map((item) => {
          obj[item.dictValue] = item.dictLabel;
        });
      }
      setByTypeList(obj);
    } else {
      setByTypeList({});
    }
  };
  const getBrandInfo = async () => {
    setLoading(true);
    let res = await Https.get("/brand/setting/findBrand", {}, true);
    setLoading(false);
    if (res.code == 200) {
      setBrandInfo(res.data);
      setBrandImg(res.data.brandLogoUrl);
      setHtml(res.data.brandIntroduce);
    } else {
      message.error(res.msg);
      setBrandInfo({});
    }
  };
  const save = async () => {
    if (!brandImg) {
      message.error("请上传品牌图片!");
      return;
    }
    let params = {
      tenantId: brandInfo.tenantId,
      brandLogoUrl: brandImg,
      brandIntroduce: html == "<p><br></p>" ? "" : html,
    };
    setLoading(true);
    let res = await Https.post("/brand/setting/updateBrand", params, true);
    setLoading(false);
    if (res.code == 200) {
      message.success("操作成功");
      dispatch({
        type: "global/queryBrandInfo",
      });
    } else {
      message.error(res.msg);
    }
  };
  useEffect(() => {
    getBrandInfo();
    getByType();
  }, []);
  return (
    <PageContainer
      className={styles.BrandBasic}
      footer={[
        <Button
          type="primary"
          size="large"
          onClick={() => {
            save();
          }}
        >
          保存更新
        </Button>,
      ]}
    >
      <div>
        <Spin spinning={loading}>
          {brandInfo.tenantId ? (
            <div style={{ width: "100%" }}>
              <Card>
                <Flex justify="flex-start" gap={24}>
                  <div>
                    {brandImg ? (
                      <div className={styles.avatar_box}>
                        <Image width={100} height={100} src={brandImg} />
                        <a
                          onClick={() => {
                            setBrandImg("");
                          }}
                        >
                          <DeleteOutlined
                            style={{ fontSize: "15px", color: "#ffffff" }}
                          />
                        </a>
                      </div>
                    ) : (
                      <UploadPreview
                        onSuccess={(e) => {
                          setBrandImg(e);
                        }}
                        btnText={"上传品牌Logo"}
                      />
                    )}
                  </div>
                  <div>
                    <div className={styles.BasicHeader}>
                      <span className={styles.brandName}>
                        {brandInfo.brandName}
                      </span>
                      <span
                        className={styles.packageName}
                        style={{ background: hexToRgba(brandInfo.color, 0.04) }}
                      >
                        <img src={brandInfo.icon} alt="" />
                        <span style={{ color: brandInfo.color }}>
                          {brandInfo.packageName}
                        </span>
                      </span>
                      <a
                        onClick={() => {
                          onSuccess("2");
                        }}
                      >
                        套餐详情{">>"}
                      </a>
                    </div>
                    <div>
                      <ProDescriptions layout="vertical">
                        <ProDescriptions.Item label="品牌ID">
                          {brandInfo.tenantId}
                        </ProDescriptions.Item>
                        <ProDescriptions.Item label="有效期至">
                          {brandInfo.isForever == "1"
                            ? "永久"
                            : brandInfo.expireTime
                            ? dayjs(brandInfo.expireTime).format("YYYY-MM-DD")
                            : ""}
                          <Tag
                            style={{ marginLeft: "10px" }}
                            color={
                              brandInfo.status == "1" ? "green" : "default"
                            }
                          >
                            {brandInfo.status == "1" ? "生效中" : "已失效"}
                          </Tag>
                        </ProDescriptions.Item>
                        <ProDescriptions.Item label="联系手机号">
                          {brandInfo.contactPhone}
                        </ProDescriptions.Item>
                        <ProDescriptions.Item
                          label="业务类型"
                          valueEnum={byTypeList}
                        >
                          {brandInfo.businessType}
                        </ProDescriptions.Item>
                        <ProDescriptions.Item label="所属区域">
                          {brandInfo.region}
                        </ProDescriptions.Item>
                        <ProDescriptions.Item
                          label="入驻时间"
                          valueType={"date"}
                        >
                          {brandInfo.verifyDate}
                        </ProDescriptions.Item>
                      </ProDescriptions>
                    </div>
                  </div>
                </Flex>
              </Card>
              <Card>
                <Flex justify="space-between">
                  <div>
                    <div style={{ fontWeight: "bold" }}>
                      微信公众号(授权成功后,会员消息会推送到公众号中)
                    </div>
                    <div>
                      1、公众号消息模板所属行业为：主营行业:IT科技/互联网|电子商务、副营行业：文体娱乐/体育；
                    </div>
                    <div>
                      2、根据微信规定，未开通的需要申请开通，微信会在1-2个工作日内审核；
                    </div>
                    <div>3、授权成功后，一个月只能修改一次；</div>
                  </div>
                  <div>
                    <Button type="primary" disabled>
                      申请授权
                    </Button>
                  </div>
                </Flex>
              </Card>
              <Card
                title={
                  <span>
                    品牌介绍
                    <Tooltip
                      title={
                        <img
                          style={{ width: "200px", height: "auto" }}
                          src={authorPng}
                        ></img>
                      }
                    >
                      <InfoCircleOutlined style={{ marginLeft: "5px" }} />
                    </Tooltip>
                  </span>
                }
              >
                <div id="courseIntroduce">
                  <Toolbar
                    editor={editor}
                    defaultConfig={{}}
                    mode="default"
                    style={{ borderBottom: "1px solid #ccc" }}
                  />
                  <Editor
                    defaultConfig={editorConfig}
                    value={html}
                    onCreated={setEditor}
                    onChange={(editor) => setHtml(editor.getHtml())}
                    mode="default"
                    style={{ height: "300px", overflowY: "hidden" }}
                  />
                </div>
              </Card>
            </div>
          ) : (
            <div style={{ minHeight: "150px" }}></div>
          )}
        </Spin>
      </div>
    </PageContainer>
  );
};
export default connect(({ global }) => ({
  ...global,
}))(BrandBasic);
